#!/usr/bin/env python
'''
Function that handles the brands
'''

import gobject
import gtk
import Breweries
import Coasters
import Gui

from DB import *
from GladeWidgets import GladeWidget

class Brand:
    '''Some constraints useful for the model'''
    NAME = 0
    BREWERY = 1
    COUNTRY = 2
    COASTERS = 3

def on_btnBrandAdd_clicked(wnd, event):
    '''Add a new brand'''
    wndBrandAdd = GladeWidget("wndAddBrand")
    _setupComboBrand(wndBrandAdd["comboBrewery"])

    res = False
    while (res == False):
        ret = wndBrandAdd["wndAddBrand"].run()
        if (ret == 1): # cancel
            res = True
        elif (ret == 2): # add
            res = _addBrand(wndBrandAdd)
            if (res == True):
                showTreeview(wnd["treeviewBrands"])
    wndBrandAdd["wndAddBrand"].destroy()

def on_btnBrandEdit_clicked(wnd, event):
    '''Edit an existing brand'''
    wndBrandEdit = GladeWidget("wndEditBrand")

    if (_setupEditWindow(wnd, wndBrandEdit) == False):
        return False

    # get the old brand name
    model, iterator = wnd["treeviewBrands"].get_selection().get_selected()
    oldname = model.get_value(iterator, Brand.NAME)

    res = False
    while (res == False):
        ret = wndBrandEdit["wndEditBrand"].run()
        if (ret == 1): # cancel
            res = True
        elif (ret == 2): # ok
            res = _editBrand(wndBrandEdit, oldname)
            if (res == True):
                showTreeview(wnd["treeviewBrands"])
                Coasters.showTreeview(wnd["treeviewCoasters"])
    wndBrandEdit["wndEditBrand"].destroy()

def on_btnBrandDel_clicked(wnd, event):
    '''Delete an existing brand'''
    model, iterator = wnd["treeviewBrands"].get_selection().get_selected()
    if not iterator:
        Gui.ErrorBox(str="Select an item to delete first!")
    else:
        yesno = gtk.MessageDialog(wnd["wndMain"], gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,
                "WARNING: deleting this brand will also delete all the coasters that are associated with it." +
                " Do you still want to delete it?")

        def delBrandResponse(window, response_id):
            if response_id == gtk.RESPONSE_YES:
                path = wnd["treeviewBrands"].get_model().get_path(iterator)[Brand.NAME]
                db = DB()
                db.delBrand(model.get_value(iterator, Brand.NAME))
                wnd["treeviewBrands"].get_model().remove(iterator)
                Coasters.showTreeview(wnd["treeviewCoasters"])
            yesno.destroy()

        yesno.connect("response", delBrandResponse)
        yesno.show()


def _setupComboBrand(combo, the_active=None):
    '''Add the brands to the combobox'''
    db = DB()
    breweries = db.getAllBreweries()
    # transform set in list
    list = []
    for brewery in breweries:
        list.append(brewery[0])
    Gui.setCombobox(combo, list, has_na=False, active=the_active)

def setTreeModel(wnd):
    '''Setup the model for the brand tree view'''
    treeview = wnd["treeviewBrands"]
    model = gtk.ListStore(  gobject.TYPE_STRING,    # brand name
                            gobject.TYPE_STRING,    # brewery
                            gobject.TYPE_STRING,    # country
                            gobject.TYPE_INT)       # no. of coasters
    treeview.set_model(model)

    # setup the cells
    Gui.treeviewAddGeneralTextColumn(treeview, "Brand name", Brand.NAME, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Brewery", Brand.BREWERY, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Country", Brand.COUNTRY, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Coasters", Brand.COASTERS, resizable=True, reorderable=True)

def showTreeview(treeview, filter='%'):
    '''Fill the treeview with brands informations (you can pass
    "filter=<sqlwildcard>" in order to show just some infos'''

    db = DB()
    brands = db.getAllBrands(filter)
    treeview.get_model().clear()
    for brand_name in brands:
        name = brand_name[0]
        brand_brewery = db.getBreweryByBrand(name)
        _addTreeviewRow(treeview, name, brand_brewery, db.getBrandCountry(name), db.getCoasterNum(name))


def _addTreeviewRow(treeview, name, brewery, country=None, coasters=0):
    '''Add a new row to the treeview'''
    model = treeview.get_model()
    item = model.append(None)
    model.set_value(item, Brand.NAME, name)
    model.set_value(item, Brand.BREWERY, brewery)
    model.set_value(item, Brand.COUNTRY, country)
    model.set_value(item, Brand.COASTERS, coasters)


def _addBrand(wnd):
    '''A wrapper to the database function that adds a new brand'''
    name = wnd["txtBrandName"].get_text()
    brewery = wnd["comboBrewery"].get_active_text()
    comments = wnd["txtComments"].get_text()

    if ((name == None) or (len(name) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brand name is required)")
        return False

    if ((brewery == None) or (len(brewery) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brewery is required)")
        return False

    if (len(comments) == 0):
        comments = None

    db = DB()
    try:
        db.addBrand(name, brewery, comments)
        return True
    except ExistingError:
        Gui.ErrorBox(str="A brand with this name is already existing")
        return False

def _editBrand(wnd, oldname):
    '''A wrapper to the database function that updates the brand'''
    name = wnd["txtName"].get_text()
    brewery = wnd["comboBreweries"].get_active_text()
    comment = wnd["txtComments"].get_text()

    if ((name == None) or (len(name) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brand name is required)")
        return False

    if ((brewery == None) or (len(brewery) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brewery is required)")
        return False

    if (len(comment) == 0):
        comment = None

    db = DB()
    try:
        db.updateBrand(oldname, name, brewery, comment)
        return True
    except IntegrityError:
        Gui.ErrorBox(str="A brand with this name is already existing")
        return False

def _setupEditWindow(wndMain, wndEdit):
    model, iterator = wndMain["treeviewBrands"].get_selection().get_selected()
    if (not iterator):
        Gui.ErrorBox(str="Select an item to edit first!")
        return False

    db = DB()
    name = model.get_value(iterator, Brand.NAME)
    comment = db.getBrandComment(name)
    if (comment == None):
        comment = ""

    wndEdit["txtName"].set_text(name)
    wndEdit["txtComments"].set_text(comment)

    brewery = model.get_value(iterator, Brand.BREWERY)
    _setupComboBrand(wndEdit["comboBreweries"], the_active=brewery)
    return True
